#include "mystdio.h"
my_FILE* my_fopen(const char* path, const char* flag){
    int n = 0;
    int mark = 0; 
    mode_t mod = 0666;
    if(strcmp(flag, "r") == 0)
    {
        n = O_RDONLY;
    }
    else if(strcmp(flag, "w") == 0)
    {
        n = O_CREAT | O_WRONLY | O_TRUNC;
        mark = 1;
    }
    else if(strcmp(flag, "a") == 0)
    {
        n = O_CREAT | O_WRONLY | O_APPEND; 
        mark = 1;
    }
    else
    {}
    int fd = 0;
    if(mark)
    {
        fd = open(path, n, mod);
    }
    else 
        fd = open(path, n);
    if(fd < 0)
        return NULL;
    my_FILE* ret = (my_FILE*)malloc(sizeof(my_FILE));
    if(!ret)  return NULL;
    ret->flags = n;
    ret->fileno = fd;
    ret->mark = FLUSH_LINE;
    ret->cap = SIZE;
    ret->pos = 0;
    return ret;
}
void my_fflush(my_FILE* fp){
    write(fp->fileno, fp->cache, fp->pos);
    fp->pos = 0;
    
}
ssize_t my_fwrite(my_FILE* fp, const char* data, int len){
    memcpy(fp->cache+fp->pos, data, len);
    fp->pos += len;
    if(fp->flags & FLUSH_LINE && fp->cache[fp->pos - 1] == '\n')
    { 
        my_fflush(fp);
    }
    return len;
}
void my_fclose(my_FILE* fp){
    my_fflush(fp);
    close(fp->fileno);
    free(fp);
}
